<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 用户答题记录表（楼梯形式答题）
 */
class AnswerActivityUserStairsAnswerRecord extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'answer_activity_user_stairs_answer_record';


    /**
     * 判断此活动是否有人答过题
     */
    public function  isBeenAnswer($id)
    {
        return $this->where('act_id', $id)->first();
    }

    /**
     * 判断是否有人答过此题
     */
    public function  isBeenProblem($id)
    {
        return $this->where('problem_id', $id)->first();
    }


    /**
     * 写入爬楼梯答题记录
     */
    public function addUserStairsRecord($data,$unit_id,$user_guid , $answer_time , $floor){
        
        $this->guid = get_guid();
        $this->act_id = $data[0]['act_id'];
        $this->user_guid = $user_guid;
        $this->unit_id = $unit_id ?: 0;
        $this->problem_id = $data[0]['id'];
        $this->floor = $floor;
        $this->status = 0;
        $this->times = $answer_time;
        $this->expire_time = date('Y-m-d H:i:s' , strtotime("+".$answer_time." second"));
        $this->save();
        
        return $this->guid;
    }

    /**
     * 修改爬楼梯答题记录
     * @param  $res 馆内答题记录对象
     */
    public function changeUserStairsRecord($res ,$answer_id ,$content, $status){
        $res->answer_id = $answer_id ?: 0;
        $res->answer = $content;
        $res->status = $status;
        $res->times = time() - strtotime($res->create_time);
        return $res->save();
    }


      /**
     * 根据guid，获取问题记录
     * @param guid
     */
    public function getStairsRecordByGuid($guid){
        $res = $this->where('guid', $guid)->first();
        return $res;
    }

     /**
     * 或者总答题时长
     * @param guid
     */
    public static function getAnswerTotalTimes($user_guid, $act_id,$unit_id=null)
    {
        $res = self::where('user_guid', $user_guid)
        ->where('act_id' , $act_id)
        ->where(function ($query) use ($unit_id) {
            if ($unit_id) {
                $query->where('unit_id', $unit_id);
            }
        })->sum('times');

        return $res;
    }



    /**
     * 获取用户回答的所有题
     * @param act_id 活动id
     * @param user_guid 用户guid
     * @param unit_id 单位id
     * @param status array 答题状态  0表示所有 1代表正确  2代表错误   3 超时回答（算错误）默认2
     */
    public function getHaveAnswer($act_id , $user_guid , $unit_id =null , $status = []){
        $res = $this->where('act_id' , $act_id)->where('user_guid' , $user_guid)->where(function($query) use($unit_id , $status){
                if($unit_id){
                    $query->where('unit_id', $unit_id);
                }
                if($status){
                    $query->whereIn('status', $status);
                }
        })->groupBy('problem_id')
        ->pluck('problem_id')
        ->toArray();

        return $res;
    }


    /**
     * 用户参与人次、答题次数统计
     * @param act_id 活动id
     * @param unit_id 单位id 数组形式
     * @param start_time 单位id 开始时间
     * @param end_time 单位id 结束时间
     * @param type 类型 1 参与人次  2 答题次数
     */
    public function partNumberStatistics($act_id, $unit_id = null, $start_time = null, $end_time = null, $type = 1)
    {
        $res = $this->select('id', 'user_guid', 'act_id')->where(function ($query) use ($act_id,$unit_id, $start_time, $end_time) {
            if ($act_id) {
                $query->where('act_id', $act_id);
            }
            if ($unit_id) {
                $query->whereIn('unit_id', $unit_id);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        });

        if ($type == 1) {
            $res = $res->groupBy('user_guid');
        }
        $result = $res->get()->toArray();

        return count($result);
    }

     /**
     * 答题次数统计(折线图)
     * @param act_id 活动id
     * @param unit_id 单位id 数组形式
     * @param start_time 单位id 开始时间
     * @param end_time 单位id 结束时间
     * @param is_month  是否按月统计
     */
    public function partStatistics($act_id, $unit_id = null, $start_time = null, $end_time = null, $is_month = false)
    {
        if (empty($start_time)) {
            $start_time = date('Y-m-d 00:00:00');
            $end_time = date('Y-m-d H:i:s');
        }

        if ($is_month) {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m') as dates"), DB::raw("count(id) as count")];
        } elseif (date('Y-m-d' , strtotime($start_time)) == date('Y-m-d' , strtotime($end_time))) {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d %H') as dates"), DB::raw("count(id) as count")];
        } else {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d') as dates"), DB::raw("count(id) as count")];
        }

        $res = $this->select($field)->where(function ($query) use ($act_id, $unit_id, $start_time, $end_time) {
            if ($act_id) {
                $query->where('act_id', $act_id);
            }
            if ($unit_id) {
                $query->whereIn('unit_id', $unit_id);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })
            ->orderBy('dates')
            ->groupBy('dates')
            ->get()
            ->toArray();

        return $res;
    }


}
